package com.zlp.jwt.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.zlp.jwt.entity.User;

import java.util.Calendar;
import java.util.Map;

/**
 * @author: zhulaiping
 * @create: 2021-12-06 17:16
 **/
public class JwtUtil {

    /**
     * 根据用户id生成token
     * @param user
     * @return
     */
    public static String getToken(User user) {
        String token = "";
        token = JWT.create().withAudience(user.getId())
                .sign(Algorithm.HMAC256(user.getPassword()));
        return token;
    }

    /**
     * 秘钥
     */
    private static final String SING="TVJGHFTY%&&^*";

    /**
     * 根据用户信息创建token
     * @param map
     * @return
     */
    public static String getToken(Map<String,String> map){
        Calendar instance = Calendar.getInstance();
        //默认7天过期
        instance.add(Calendar.DATE,7);
        //创建jwt  builder
        JWTCreator.Builder builder = JWT.create();
        //创建payload
        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });
        //指定令牌过期时间
        String token = builder.withExpiresAt(instance.getTime())
                //指定令牌的加密算法
                .sign(Algorithm.HMAC256(SING));
        return token;
    }

    /**
     * 验证token，成功返回解析对象
     * @param token
     * @return
     */
    public static DecodedJWT verify(String token){
        return JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
    }
}
